<template>
  <div class="chat-container">
    <!-- 左侧聊天会话列表组件 -->
    <ChatSessionList 
      :sessions="sessions" 
      :current-session="currentSession" 
      :userId="userId"
      @select-session="selectSession"
      @new-session="openNewSession"
      @delete-session="handleDeleteSession" />

    <!-- 右侧聊天窗口组件 -->
    <ChatWindow ref="chatWindow" :messages="messages" :current-session="currentSession"
      @send-message="handleSendMessage" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import ChatApi from '@/api/request.js'
import baseUrl from '@/api/baseUrl.ts';
import ChatSessionList from '@/components/ChatSessionList.vue';
import ChatWindow from '@/components/ChatWindow.vue';
import { ElMessage } from 'element-plus';

// 聊天窗口组件引用
const chatWindow = ref(null);
// 聊天会话列表
const sessions = ref([]);
// 当前选中的会话
const currentSession = ref({});
// 聊天记录
const messages = ref([]);
// 定义事件源的引用，用于实时通信
const eventSource = ref(null);
// 用户ID
const userId = ref(localStorage.getItem('WANGANUI_USER') || '');

// 选择会话
const selectSession = (session) => {
  currentSession.value = session;
  messages.value = [];
  // 查询当前会话聊天记录
  loadMessages();
};

// 创建新会话
const openNewSession = () => {
  messages.value = [];
  currentSession.value = {};
};

// 处理发送消息
const handleSendMessage = (messageText) => {
  if (!currentSession.value.sessionId) {
    // 添加一个模拟的新Session
    const sessionId = '';
    const sessionName = messageText.length >= 15 ? messageText.substring(0, 15) + '...' : messageText;
    sessions.value = [{
      sessionName,
      sessionId
    }].concat(sessions.value);
  }
  if (eventSource.value != null) {
    eventSource.value.close();
  }
  // 将用户输入的消息添加到消息列表中，并设置消息类型为用户发送
  messages.value.push({
    msg: messageText,
    type: 1
  });
  messages.value.push({
    msg: '',
    type: 3
  });

  let messageOrigin = '';

  const apiBaseUrl = baseUrl + "api/chat/ai/generateStream";
  const encodedValue = encodeURIComponent(messageText);
  const encodedSessionId = currentSession.value?.sessionId ? encodeURIComponent(currentSession.value.sessionId) : '';
  const userId = localStorage.getItem('WANGANUI_USER') || '';

  eventSource.value = new EventSource(`${apiBaseUrl}?message=${encodedValue}&sessionId=${encodedSessionId}&userId=${userId}`);
  eventSource.value.onmessage = function (event) {
    if (messageOrigin.length === 0) {
      // 删除 type:3 的消息
      messages.value = messages.value.filter(message => message.type !== 3);
      // 增加 type:2 的消息
      messages.value.push({
      msg: '',
      type: 2
      });
    }
    try {
      let substring = event.data.replaceAll("data:", "");
      let parse = JSON.parse(substring);
      messageOrigin += parse.result?.output?.text;
      if (parse.result?.metadata?.finishReason === "stop") {
        messageOrigin = messageOrigin.replace("<think>", "<div class='think'>").replace("</think>", "</div>");
        eventSource.value.close();
      }
      messages.value[messages.value.length - 1].msg = messageOrigin;
      // 调用聊天窗口组件的滚动方法
      chatWindow.value.scrollToBottom();
      if (!currentSession.value.sessionId) {
        init(false);
      }
    } catch (error) {
      console.error("消息异常:", error);
    }
  };
  eventSource.value.onerror = function (event) {
    eventSource.value.close();
  };
  eventSource.value.onclose = function (event) {
    console.log("事件关闭:", event);
  };
};

// 处理删除会话
const handleDeleteSession = (sessionId) => {
  // 从会话列表中移除已删除的会话
  sessions.value = sessions.value.filter(s => s.sessionId !== sessionId);
  
  // 如果删除的是当前选中的会话，则清空当前会话和消息列表
  if (currentSession.value && currentSession.value.sessionId === sessionId) {
    currentSession.value = sessions.value.length > 0 ? sessions.value[0] : {};
    messages.value = [];
    
    // 如果还有其他会话，则加载第一个会话的消息
    if (sessions.value.length > 0) {
      loadMessages();
    }
  }
};

/**
 * 初始化会话列表
 * @param init 是否初次加载
 */
const init = (init) => {
  // 设置一个默认的用户ID，并存储到缓存
  if (!userId.value) {
    userId.value = String(new Date().getTime());
    localStorage.setItem('WANGANUI_USER', userId.value);
  }
  ChatApi.API.getSession(userId.value).then(res => {
    sessions.value = res.data;
    currentSession.value = sessions?.value[0];
    if (sessions.value.length > 0 && init) {
      // 查询当前会话聊天记录
      loadMessages();
    }
  });
};

// 在组件挂载时调用初始化函数
onMounted(() => {
  console.log('聊天页面加载，初始化数据...');
  init(true);
});

// 查询聊天记录
const loadMessages = () => {
  ChatApi.API.getMessages(currentSession.value.sessionId).then(res => {
    res.data.forEach(item => {
      if (item.messageType === 'USER') {
        messages.value.push({
          msg: item.text,
          type: 1
        });
      } else {
        const text = item.text.replaceAll("<think>", "<div class='think'>").replaceAll("</think>", "</div>");
        messages.value.push({
          msg: text,
          type: 2
        });
      }
    });
  });
  setTimeout(() => {
    chatWindow.value.scrollToBottom();
  }, 200);
};
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  height: calc(100vh - 150px);
  padding: 20px;
  gap: 20px;
  background-color: #f5f7fa;
  border-radius: 16px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.05);
  /* 加深阴影效果 */
  border: 1px solid rgba(216, 218, 219, 0.15);
  /* 添加淡蓝色边框 */

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(245, 247, 250, 0.6) 100%);
    border-radius: 16px;
    z-index: -1;
  }
}

@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
    height: auto;
  }
}
</style>